import fs from 'fs'
import express from 'express'

// 判断是否是生产环境
const isProduction = process.env.NODE_ENV === 'production'
const app = express()

let vite
if (!isProduction) {
  // 开发环境
  const { createServer: createViteServer } = await import('vite')
  vite = await createViteServer({
    server: { middlewareMode: true },
    appType: 'custom' // 'spa'
  })
  app.use(vite.middlewares)
} else {
  // 生产环境
  // app.use(express.static('dist/client'))
  const sirv = (await import('sirv')).default
  app.use('/', sirv('./dist/client', { extensions: [] }))
}

app.use(async (req, res) => {
  let template
  let render
  if (!isProduction) {
    template = fs.readFileSync('./index.html', 'utf-8')
    template = await vite.transformIndexHtml(req.originalUrl, template)
    render = (await vite.ssrLoadModule('/src/entry-server.ts')).default
  } else {
    template = fs.readFileSync('./dist/client/index.html', 'utf-8')
    render = (await import('./dist/server/entry-server.js')).default
  }
  const appHtml = await render(req.originalUrl)
  const responseHtml = template.replace(`<!-- 占位 -->`, appHtml)
  res.set('content-type', 'text/html').send(responseHtml)
})

app.listen(4396, () => console.log('server is running'))
